package com.spz.demo.scloud.consumer.controller;

import com.spz.demo.scloud.common.core.bean.RestBean;
import com.spz.demo.scloud.common.service.AppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * 注册中心 - Eureka - 测试接口
 */
@Slf4j
@RestController
@RequestMapping("/discovery/eureka")
public class DiscoveryEurekaController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 服务远程调用测试 - 使用 RestTemplate
     * @see AppService#instanceNameAndPort()
     * @return
     */
    @RequestMapping("/appService/projectInfo")
    public RestBean appServiceProjectInfo(){
        RestBean restBean = restTemplate.postForObject("http://MS-PROVIDER/projectInfo",null, RestBean.class);
        return restBean;
    }

    /**
     * 获取已在 Eureka Server 注册的服务名称列表
     * 注意不是服务名下的实例名称列表，是 Eureka的Application名称列表
     * @return
     */
    @RequestMapping("/services")
    public RestBean services(){
        List<String> services = discoveryClient.getServices();
        return RestBean.ok(services);
    }

    /**
     * 根据名称获取实例列表
     * 1. 如多个服务注册到Eureka服务端，他们的名称均为MS-PROVIDER，则使用MS-PROVIDER可查询出所有已注册实例
     * 2. 获取到ServiceInstance对象里包含实例的ServiceId、host、port、uri等
     * @param name eg. MS-PROVIDER
     * @return
     */
    @GetMapping("/instances/{name}")
    public RestBean instancesByName(@PathVariable(name = "name", required = true) String name){
        List<ServiceInstance> instances = discoveryClient.getInstances(name);
        return RestBean.ok(instances);
    }
}
